﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using ChatDAL;

namespace ChatNamespace
{
    public class Chat
    {
        private ChatContext context;

        public Chat()
        {
            this.context = new ChatContext();
        }

        public List<Channel> ListAllChannels()
        {
            var result =
                from c in this.context.Channels
                orderby c.Name
                select c;

            return result.ToList();
        }

        public Message[] ShowLastMessages(string channelName, int numberOfMessages)
        {
            var channel = this.context.Channels.FirstOrDefault(c => c.Name == channelName);
            var messages = this.context.Messages.Where(m => m.ChannelID == channel.ChannelID);

            if (messages.ToArray().Length < numberOfMessages)
            {
                return messages.ToArray();
            }
            else
            {
                var lastMessages = messages.Skip(Math.Max(0, this.context.Messages.Count() - numberOfMessages)).Take(numberOfMessages);
                return lastMessages.ToArray();
            }
        }

        public void CreateNewChannel(Channel channelToAdd)
        {
            var channel = this.context.Channels.FirstOrDefault(c => c.Name == channelToAdd.Name);

            if (channel == null)
            {
                this.context.Add(channelToAdd);
                this.context.SaveChanges();
            }
            else
            {
                var messages = this.context.Messages.Where(m => m.ChannelID == channelToAdd.ChannelID);

                foreach (var message in messages)
                {
                    this.context.Delete(message);
                }
                this.context.SaveChanges();
            }
        }

        public void PostNewMessage(Message message)
        {
            this.context.Add(message);
            this.context.SaveChanges();
        }
    }
}
